/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
   Module Name          : com.yaodian100.crm.workorder.remote.RemoteWorkOrderServiceImpl
   Module Description   :

   Date Created      : 2011/3/8
   Original Author   : cut7man
   Team              : yaodian100
   ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
   MODIFICATION HISTORY
   ------------------------------------------------------------------------------
   Date Modified       Modified by       Comments
   ------------------------------------------------------------------------------
   ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
package com.yaodian100.crm.workorder.remote;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.beans.BeanUtils;

import com.yaodian100.core.admin.entity.User;
import com.yaodian100.core.common.service.BaseManager;
import com.yaodian100.core.common.utils.StringUtils;
import com.yaodian100.crm.cs.entity.QuestionExtraValue;
import com.yaodian100.crm.cs.service.CsService;
import com.yaodian100.crm.workorder.entity.WorkOrder;
import com.yaodian100.crm.workorder.service.WorkOrderService;
import com.yaodian100.ec.order.entity.OrderProduct;
import com.yaodian100.ec.order.entity.Orders;
import com.yaodian100.ec.order.service.ServiceOrderService;
import com.yaodian100.ec.product.service.OrderCommentService;

/**
 * @author cut7man
 * 
 */
public class RemoteWorkOrderServiceImpl implements RemoteWorkOrderService {
	@Resource
	private CsService csService;
	@Resource
	private BaseManager baseMgr;
	@Resource
	private WorkOrderService workOrderService;
	@Resource
	private ServiceOrderService serviceOrderService;
	@Resource
	private OrderCommentService orderCommentService;

	@Override
	public String commentToWorkorder(int rows) {
		if (orderCommentService.commentToWorkorder(rows)) {
			return "true";
		} else {
			return "false";
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.yaodian100.crm.workorder.remote.RemoteWorkOrderService#forwardOrderForOutOfStockInternal(java.lang.String,
	 * java.lang.String, java.lang.String, java.lang.String)
	 */
	@Override
	public String forwardOrderForOutOfStockInternal(String orderId, String productIds, String reason, String comment,
			String creater) {
		try {
			csService.forwardOrderForOutOfStockInternal(orderId, productIds, reason, comment, creater);
		} catch (Exception e) {
			String execLog = StringUtils.printExecption(null, e);
			return execLog;
		}
		return "true";
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.yaodian100.crm.workorder.remote.RemoteWorkOrderService#statementOutOfStockWorkOrder()
	 */
	@Override
	public String closeWorkOrderForOutOfStockOfDay(String day) {
		try {
			workOrderService.closeWorkOrderForOutOfStockOfDay(day);
		} catch (Exception e) {
			return "false";
		}
		return "true";
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.yaodian100.crm.workorder.remote.RemoteWorkOrderService#chkServiceOrderByOrderId(java.lang.String)
	 */
	@Override
	public String chkServiceOrderByOrderId(String orderId) {
		return workOrderService.chkServiceOrderByOrderId(orderId);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.yaodian100.crm.workorder.remote.RemoteWorkOrderService#updOrderStatusToShipped(java.lang.String)
	 */
	@Override
	public String updOrderStatusTo30ByOrderId(String orderId) {
		return workOrderService.updOrderStatusTo30ByOrderId(orderId);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.yaodian100.crm.workorder.remote.RemoteWorkOrderService#chkServiceOrderByServiceId(java.lang.String)
	 */
	@Override
	public String chkServiceOrderByServiceId(String serviceId) {
		return workOrderService.chkServiceOrderByServiceId(serviceId);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.yaodian100.crm.workorder.remote.RemoteWorkOrderService#updServiceOrderStatusTo20ByServiceId(java.lang.String)
	 */
	@Override
	public String updServiceOrderStatusTo20ByServiceId(String serviceId) {
		return workOrderService.updServiceOrderStatusTo20ByServiceId(serviceId);
	}

	@Override
	public Long countWorkOrder(String responseGroup, String ownerUsername, String memberId, String orderId,
			String workOrderId, String questionId) {
		String hql = "from WorkOrder w where w.responseGroup=? ";
		List<Object> params = new ArrayList<Object>();
		params.add(responseGroup);
		if (ownerUsername != null && ownerUsername.length() > 0) {
			hql += "and w.owner.username=? ";
			params.add(ownerUsername);
		}
		if (memberId != null && memberId.length() > 0) {
			hql += "and w.question.memberId=? ";
			params.add(memberId);
		}
		if (orderId != null && orderId.length() > 0) {
			hql += "and w.question.extraValue['orderId'].value=? ";
			params.add(orderId);
		}
		if (workOrderId != null && workOrderId.length() > 0) {
			hql += "and w.id=? ";
			params.add(Long.valueOf(workOrderId));
		}
		if (questionId != null && questionId.length() > 0) {
			hql += "and w.question.id=? ";
			params.add(questionId);
		}
		return baseMgr.countByHql(hql, params.toArray());
	}

	@Override
	public RemoteWorkOrder[] queryWorkOrder(String responseGroup, String ownerUsername, String memberId, String orderId,
			String workOrderId, String questionId, int start, int max) {
		String hql = "from WorkOrder w where w.responseGroup=? ";
		List<Object> params = new ArrayList<Object>();
		params.add(responseGroup);
		if (ownerUsername != null && ownerUsername.length() > 0) {
			hql += "and w.owner.username=? ";
			params.add(ownerUsername);
		}
		if (memberId != null && memberId.length() > 0) {
			hql += "and w.question.memberId=? ";
			params.add(memberId);
		}
		if (orderId != null && orderId.length() > 0) {
			hql += "and w.question.extraValue['orderId'].value=? ";
			params.add(orderId);
		}
		if (workOrderId != null && workOrderId.length() > 0) {
			hql += "and w.id=? ";
			params.add(Long.valueOf(workOrderId));
		}
		if (questionId != null && questionId.length() > 0) {
			hql += "and w.question.id=? ";
			params.add(questionId);
		}
		hql += "order by w.status asc, w.createDate desc";
		Object[] result = baseMgr.queryByHql(hql, params.toArray(), start, max);
		RemoteWorkOrder[] workOrders = new RemoteWorkOrder[result.length];
		for (int i = 0; i < result.length; i++) {
			WorkOrder wo = (WorkOrder) result[i];
			RemoteWorkOrder rwo = new RemoteWorkOrder();
			BeanUtils.copyProperties(wo, rwo);
			if (wo.getNode() != null) {
				rwo.setNodeId(wo.getNode().getId());
			}
			if (wo.getOwner() != null) {
				rwo.setOwnerUsername(wo.getOwner().getUsername());
			}
			Map<String, QuestionExtraValue> evs = wo.getQuestion().getExtraValue();
			if (evs != null) {
				QuestionExtraValue qev = evs.get("orderId");
				if (qev != null) {
					rwo.setOrderId(qev.getValue());
				}
			}
			if (wo.getParent() != null) {
				rwo.setParentWorkOrderId(wo.getParent().getId());
			}
			if (wo.getQuestion().getExtraValue() != null && wo.getQuestion().getExtraValue().get("orderId") != null
					&& wo.getQuestion().getExtraValue().get("orderId").getValue() != null) {
				rwo.setOrderId(wo.getQuestion().getExtraValue().get("orderId").getValue());

				Orders o = (Orders) baseMgr.get(Orders.class, wo.getQuestion().getExtraValue().get("orderId").getValue());
				if (o != null) {
					for (int j = 0; j < o.getOrderProduct().size(); j++) {
						OrderProduct op = o.getOrderProduct().get(j);
						if (op.getLogisticNo() != null) {
							rwo.setLogisticNo(op.getLogisticRefNum());
							break;
						}
					}
				}
			}
			workOrders[i] = rwo;
		}
		return workOrders;
	}

	@Override
	public RemoteWorkOrder getWorkOrder(String workOrderId, String username) {
		WorkOrder wo = (WorkOrder) baseMgr.get(WorkOrder.class, Long.valueOf(workOrderId));
		if (wo.getOwner() != null) {
			return null;
		} else {
			User user = (User) baseMgr.get(User.class, username);
			wo.setOwner(user);
			baseMgr.update(wo);
			RemoteWorkOrder rwo = new RemoteWorkOrder();
			BeanUtils.copyProperties(wo, rwo);
			if (wo.getOwner() != null) {
				rwo.setOwnerUsername(wo.getOwner().getUsername());
			}
			if (wo.getParent() != null) {
				rwo.setParentWorkOrderId(wo.getParent().getId());
			}
			if (wo.getQuestion().getExtraValue() != null && wo.getQuestion().getExtraValue().get("orderId") != null) {
				rwo.setOrderId(wo.getQuestion().getExtraValue().get("orderId").getValue());

				Orders o = (Orders) baseMgr.get(Orders.class, wo.getQuestion().getExtraValue().get("orderId").getValue());
				for (int i = 0; i < o.getOrderProduct().size(); i++) {
					OrderProduct op = o.getOrderProduct().get(i);
					if (op.getLogisticNo() != null) {
						rwo.setLogisticNo(op.getLogisticRefNum());
						break;
					}
				}
			}

			return rwo;
		}
	}

	@Override
	public RemoteWorkOrder viewWorkOrder(String workOrderId) {
		WorkOrder wo = (WorkOrder) baseMgr.get(WorkOrder.class, Long.valueOf(workOrderId));
		RemoteWorkOrder rwo = new RemoteWorkOrder();
		BeanUtils.copyProperties(wo, rwo);
		if (wo.getOwner() != null) {
			rwo.setOwnerUsername(wo.getOwner().getUsername());
		}
		if (wo.getParent() != null) {
			rwo.setParentWorkOrderId(wo.getParent().getId());
		}
		if (wo.getQuestion().getExtraValue() != null && wo.getQuestion().getExtraValue().get("orderId") != null
				&& wo.getQuestion().getExtraValue().get("orderId").getValue() != null) {
			rwo.setOrderId(wo.getQuestion().getExtraValue().get("orderId").getValue());

			Orders o = (Orders) baseMgr.get(Orders.class, wo.getQuestion().getExtraValue().get("orderId").getValue());
			for (int i = 0; i < o.getOrderProduct().size(); i++) {
				OrderProduct op = o.getOrderProduct().get(i);
				if (op.getLogisticNo() != null) {
					rwo.setLogisticNo(op.getLogisticRefNum());
					break;
				}
			}
		}
		return rwo;
	}

	@Override
	public RemoteWorkOrder closeOrder(String workOrderId, String comment) {
		WorkOrder wo = (WorkOrder) baseMgr.get(WorkOrder.class, Long.valueOf(workOrderId));
		workOrderService.closeOrder(wo.getDomainId(), null, "false", workOrderId, comment,
				WorkOrder.FINISH_TYPE.SELF.value(), null, null, null, null);
		wo = (WorkOrder) baseMgr.get(WorkOrder.class, wo.getId());
		RemoteWorkOrder rwo = new RemoteWorkOrder();
		BeanUtils.copyProperties(wo, rwo);
		return rwo;
	}

	@Override
	public RemoteWorkOrderDetail[] queryWorkOrderForExport(String responseGroup, String status) {
		String sql = "select " + "distinct " + "wo.domainid DOMAINID, " + "wo.work_Order_Id WORKORDERID, "
				+ "wo.owner_User_name USERNAME, " + "wo.shortDesc SHORTDESC, " + "wo.note NOTE, "
				+ "wo.order_Comment ORDERCOMMENT, " + "ev.value ORDERID, " + "p.logistic_company LOGISTICCOMPANY, "
				+ "p.logistic_ref_num LOGISTICREFNUM, " + "p.logistic_st LOGISTICST, "
				+ "to_char(wo.createdate,'yyyy-mm-dd HH:mm') CREATEDATE " + "from " + "crm_work_order wo, "
				+ "crm_question_ev ev, " + "ec_order_product p " + "where " + "wo.domainid=ev.question_id "
				+ "and ev.name='orderId' " + "and ev.value is not null " + "and ev.value=p.order_id "
				+ "and wo.responseGroup=? " + "and wo.status=?";

		Object[] result = baseMgr.queryBySql(sql, new Object[] { responseGroup, status });
		RemoteWorkOrderDetail[] rwods = null;
		if (result != null && result.length > 0) {
			rwods = new RemoteWorkOrderDetail[result.length];
		}
		for (int i = 0; i < result.length; i++) {
			Map valueMap = (Map) result[i];
			RemoteWorkOrderDetail rwod = new RemoteWorkOrderDetail();
			rwod.setCreateDate((String) valueMap.get("CREATEDATE"));
			rwod.setLogisticRefNum((String) valueMap.get("LOGISTICREFNUM"));
			rwod.setLogisticSt((String) valueMap.get("LOGISTICST"));
			rwod.setNote((String) valueMap.get("NOTE"));
			rwod.setOrderComment((String) valueMap.get("ORDERCOMMENT"));
			rwod.setOrderId((String) valueMap.get("ORDERID"));
			rwod.setOwnerUsername((String) valueMap.get("USERNAME"));
			rwod.setQuestionId((String) valueMap.get("DOMAINID"));
			rwod.setShortDesc((String) valueMap.get("SHORTDESC"));
			rwod.setWorkOrderId((String) valueMap.get("WORKORDERID"));
			rwod.setLogisticCompany((String) valueMap.get("LOGISTICCOMPANY"));
			rwods[i] = rwod;
		}

		return rwods;
	}

	// 雖然這是serviceorder的作業，但是為了作業設定方便對方指定要放在這裡
	@Override
	public String cancelServiceOrderByERP(String serviceId) {
		try {
			return serviceOrderService.cancelServiceOrderByERP(serviceId);
		} catch (Exception e) {
			return "cancelServiceOrderByERP-" + e.getMessage();
		}

	}

	/**
	 * 建立配送异常工单
	 */
	@Override
	public String createFailDeliverWorkOrder(String orderId, String serviceOrderId, String woCreater, String woContent) {
		csService.createFailDeliverCancelOrder(woCreater, woContent, orderId, serviceOrderId);
		return "true";
	}
}
